﻿using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SaiPuLSCoffee.model
{
    public class SocketServer
    {
        private static SocketServer instance;
        private SocketServer() { }
        public static SocketServer Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new SocketServer();
                }
                return instance;
            }
        }
        public static Socket serverSocket;
        /// <summary>
        /// 点单屏连接
        /// </summary>
        public Socket CoffeeSocket;
        /// <summary>
        /// 控制屏连接
        /// </summary>
        public Socket PMSocket;
        private static int myProt = 8885;  //端口 
        private static byte[] result = new byte[4096];
        /// <summary>
        /// 服务器启动监听各种信息动态
        /// </summary>
        public void CoffeeMake()
        {
            try
            {
                string LocalIP = "192.168.0.77";
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ips in host.AddressList)
                {
                    if (ips.AddressFamily == AddressFamily.InterNetwork)
                    {
                        LocalIP = ips.ToString();
                        // Console.WriteLine"IP Address = " + (ips.ToString());
                    }
                }
                //服务器IP地址 
                IPAddress ip = IPAddress.Parse(LocalIP);
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址：端口 
                serverSocket.Listen(10);  //设定最多10个排队连接请求 
                Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
                //通过Clientsoket发送数据 
                Thread myThread = new Thread(ListenClientConnect);
                myThread.IsBackground = true;
                myThread.Start();
                //foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses())
                //{
                //    if (thisProc.ProcessName == "DubaiCoffee")
                //    {
                //        if (!thisProc.CloseMainWindow())
                //            thisProc.Kill(); //当发送关闭窗口命令无效时强行结束进程     
                //    }
                //}
                //Process ps = new Process();
                //string yourURL = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"coffee";
                //ps.StartInfo.FileName = "DubaiCoffee.exe";
                //ps.StartInfo.WorkingDirectory = yourURL;
                //ps.Start();
            }
            catch (Exception ex)
            {
                serverSocket.Shutdown(SocketShutdown.Both);
                serverSocket.Close();
                CoffeeMake();
                return;
            }
        }
        /// <summary> 
        /// 监听客户端连接 
        /// </summary> 
        private void ListenClientConnect()
        {
            try
            {
                while (true)
                {
                    Socket clientSocket = serverSocket.Accept();
                    string ip = ((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString();
                    Console.WriteLine("点单");
                    Thread receiveThread = new Thread(ReceiveMessage);
                    receiveThread.IsBackground = true;
                    receiveThread.Start(clientSocket);
                    Thread.Sleep(10);
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        /// <summary> 
        /// 接收消息 
        /// </summary> 
        /// <param name="clientSocket"></param> 
        private void ReceiveMessage(object clientSockets)
        {
            Socket myClientSocket = (Socket)clientSockets;

            while (true)
            {
                try
                {
                    //通过clientSocket接收数据 
                    int receiveNumber = myClientSocket.Receive(result);
                    if (receiveNumber == 0) continue;
                    try
                    {
                        var msg = Encoding.UTF8.GetString(result, 0, receiveNumber);
                        if (msg.Trim().Length != 0)
                        {
                            var making = JsonConvert.DeserializeObject<ClientList>(msg);
                            if (making != null)
                            {
                                if (making.code == 4)
                                {
                                    CoffeeSocket = myClientSocket;
                                }
                                else if (making.code == 6)
                                {
                                    PMSocket = myClientSocket;
                                }
                                else if (making.code == 5)
                                {
                                    CoffeeMakes.Instance.coffeeInits.Add(making.coffeeInit);
                                }
                            }
                        }
                        Thread.Sleep(10);
                    }
                    catch (Exception)
                    {
                    }
                }
                catch (Exception ex)
                {
                    break;
                }
            }

        }
    }
}
